package design.patterns.structural;

/**
 * 享元模式
 * 解释：
 *享元模式是一种结构型设计模式，
 * 它摒弃了在每个对象中保存所有数据的方式，
 * 通过共享多个对象所共有的相同状态，
 * 让你能在有限的内存容量中载入更多对象。
 */

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 情景
 * 同一个品牌的共享单车
 * 不变：外观的样式
 * 变：编号
 *
 *
 * 那么不变的属性 将会存在Factory中，复用
 * 变的属性独立处理
 */
public class F_Flyweight {
    public static void main(String[] args) {
        SharedBike yellowBike1 = new SharedBike("1", BikeStyleFactory.getBikeStyle("黄色"));
        SharedBike yellowBike2 = new SharedBike("2", BikeStyleFactory.getBikeStyle("黄色"));
        SharedBike yellowBike3 = new SharedBike("3", BikeStyleFactory.getBikeStyle("黄色"));
        System.out.println("共创建了 "+BikeStyleFactory.createInstanceTimes +"  个BikeStyle实例");

        SharedBike greenBike1 = new SharedBike("4", BikeStyleFactory.getBikeStyle("绿色"));
        System.out.println("共创建了 "+BikeStyleFactory.createInstanceTimes +"  个BikeStyle实例");

    }
}

class BikeStyle {
    private String color;

    public BikeStyle(String color) {
        this.color = color;
    }
}
class SharedBike {
    private String serialNumber;
    private BikeStyle bikeStyle;

    public SharedBike(String serialNumber, BikeStyle bikeStyle) {
        this.serialNumber = serialNumber;
        this.bikeStyle = bikeStyle;
    }

}

class BikeStyleFactory {
    static AtomicInteger createInstanceTimes = new AtomicInteger(0);
    static Map<String, BikeStyle> bikeStyleList = new HashMap<>();

    public static BikeStyle getBikeStyle(String color){
        BikeStyle result = bikeStyleList.get(color);
        if (result==null){
            createInstanceTimes.incrementAndGet();
            result = new BikeStyle(color);
            bikeStyleList.put(color,result);
            return result;
        }
        return result;
    }

}